package com.maegul.web.pages;

import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.maegul.service.UserService;
import com.maegul.service.exception.MaegulException;
import com.maegul.web.models.POJO.Signup;
import com.maegul.web.pages.base.BasePage;

public class NewUserPage extends BasePage {

	private static final long serialVersionUID = 1L;

	public NewUserPage() {
		super(NEW_USER_HEADER, NEW_USER_HEADER);
		add(new FeedbackPanel("feedback_signup"));
		add(new SignUpForm("signup_form"));

	}

	private static class SignUpForm extends StatelessForm<Signup> {

		private static final long serialVersionUID = 1L;

		@SpringBean
		private UserService userService;

		public SignUpForm(String id) {
			super(id);

			Signup signup = new Signup();
			setModel(new CompoundPropertyModel<Signup>(signup));
			add(new RequiredTextField<String>("username"));
			add(new PasswordTextField("password"));
			add(new PasswordTextField("password_check"));
			add(new RequiredTextField<String>("full_name"));
			add(new RequiredTextField<String>("mail"));
			add(new RequiredTextField<String>("mail_check"));
		}

		@Override
		public final void onSubmit() {
			Signup signup = getModelObject();

			if (signup.getPassword().equals(signup.getPassword_check())) {
				if (signup.getMail().equals(signup.getMail_check())) {
					try {
						userService.createUser(signup.getUsername(),
								signup.getPassword(), signup.getMail(),
								signup.getFull_name());
						if (!continueToOriginalDestination())
							setResponsePage(getApplication().getHomePage());
					} catch (MaegulException e) {
						error(e);
					}
				} else
					error("Mail fields do not match");
			} else
				error("Password fields do not match");
		}

	}

}
